package org.funny.machine32.software.asm;

import org.funny.machine32.base.OperationEnum;
import org.funny.machine32.utils.BinUtils;

public class Assembler {

    public static byte[] generateMachineCode(OperationEnum operation, int[] operand) {
        String mask = operation.getMask();
        if (mask.contains("f")) {
            mask = replaceMask(mask, 'f', operand[0]);
        }
        if (mask.contains("s")) {
            mask = replaceMask(mask, 's', operand[1]);
        }
        if (mask.contains("t")) {
            mask = replaceMask(mask, 't', operand[2]);
        }
        int result = BinUtils.binaryStringToInt(mask);
        return BinUtils.intToByteArray(result);
    }

    private static String replaceMask(String mask, char c, int operand) {
        int length = maskCount(mask, c);
        String string = BinUtils.intToBinaryString(operand, length);
        mask.replace(makeString(length, c), string);
        return mask;
    }

    private static int maskCount(String mask, char c) {
        char[] chars = mask.toCharArray();
        int count = 0;
        for (char ch : chars) {
            if (ch == c) {
                count++;
            }
        }
        return count;
    }

    private static String makeString(int length, char c) {
        char[] chars = new char[length];
        for (int i = 0; i < length; i++) {
            chars[i] = c;
        }
        return new String(chars);
    }

}
